package com.example.groupchatdemo.client;

import com.example.groupchatdemo.handler.GroupChatClientHandler;
import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * @Author: ZhaoJie
 * @Date: 2022/3/28
 * @Description :
 * @Modify :
 * ===================================================
 * Modifier        Modifytime        Description
 * ===================================================
 */
public class ChatGroupClient {
    
    /**
     * 私有属性
     */
    private final String host;
    private final int port;
    
    public ChatGroupClient(String host, int port) {
        this.port = port;
        this.host = host;
    }
    
    /**
     * @author: zhaojie
     * @date: 2022/3/28
     * @description: 
     * @method: run:
     * @param: 
     * @class:  ChatGroupClient
     * @return: 
     */
    public void run() throws Exception {
        EventLoopGroup clientGroup = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap()
                    .group(clientGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();

                            pipeline.addLast("decoder", new StringDecoder());
                            pipeline.addLast("encoder", new StringEncoder());
                            pipeline.addLast(new GroupChatClientHandler());
                        }
                    });

            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            //得到channel
//            channelFuture.channel().writeAndFlush("Hello Netty Server, I am a common client");
//            channelFuture.channel().closeFuture().sync();
//             通过扫描器获取文本信息
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String message = scanner.nextLine();
                channelFuture.channel().writeAndFlush(message + "\n");
            }
        } finally {
            clientGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        new ChatGroupClient("127.0.0.1", 7000).run();
    }
    
}
